package eu.codlab.androidemu.gbcdroid;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.BaseAdapter;

import eu.codlab.androidemu.utilities.GameLoader;
import eu.codlab.src.game.R;

public class FileChooserAdapter extends BaseAdapter {
	private ArrayList<String> _item;
	private ListListener _listener;
	private Context context;
	private File _currentDir;

	public FileChooserAdapter(Context context, ListListener e,ArrayList<String> items, File currentDir) {
		_currentDir = currentDir;
		_item=items;
		_listener = e;
		this.context = context;
	}

	public View getView(int pos, View inView, ViewGroup parent) {
		final int position=pos;
		View v = inView;
		if(v == null){
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.file_folder, null);
		}
		TextView bTitle = (TextView) v.findViewById(R.file.name);
		bTitle.setText(_item.get(pos));

		ImageView v2 = (ImageView)v.findViewById(R.file.type);
		String img = GameLoader.getGameMainImage(new File(_currentDir, _item.get(pos)).getAbsolutePath());
		if(_item.get(pos).endsWith(".gb")){
			if(img != null){
				Bitmap imagebmp = BitmapFactory.decodeFile(img);
				v2.setImageBitmap(imagebmp);
			}else
				v2.setImageResource(R.drawable.gb);
		}else if(_item.get(pos).endsWith(".gbc")){
			if(img != null){
				Bitmap imagebmp = BitmapFactory.decodeFile(img);
				v2.setImageBitmap(imagebmp);
			}else
				v2.setImageResource(R.drawable.gbc);
		}else if(_item.get(pos).endsWith(".gba")){
			if(img != null){
				Bitmap imagebmp = BitmapFactory.decodeFile(img);
				v2.setImageBitmap(imagebmp);
			}else
				v2.setImageResource(R.drawable.gba);
		}else if("..".equals(_item.get(pos)) || _item.get(pos).endsWith("/")){
			v2.setImageResource(R.drawable.folder);
		}else if(_item.get(pos).endsWith(".zip")){
			if(img != null){
				Bitmap imagebmp = BitmapFactory.decodeFile(img);
				v2.setImageBitmap(imagebmp);
			}else
				v2.setImageResource(R.drawable.zip);
		}else
			v2.setImageResource(R.drawable.file);

		v.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				_listener.onListItemClick(_item.get(position), v, position, position);
			}
		});
		return(v);
	}

	@Override
	public int getCount() {
		return _item.size();
	}

	@Override
	public Object getItem(int pos) {
		return _item.get(pos);//_items[arg0];
	}

	@Override
	public long getItemId(int pos) {
		return pos;//_items[arg0];
	}
}
